﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace TechMadeira.Data.Classes
{
    public class Order : Semantic, IOrder
    {
        private static int Counter = 0;

        #region Fields
        private IClient mClient = null;
        private List<IOrderItem> mOrderItems = new List<IOrderItem>(); 
        #endregion

        public Order()
        {
            Number = ++Counter;
        }

        private int mNumber = default( int );

        public int Number
        {
            get { return mNumber; }
            set { mNumber = value; Notify( this ); }
        }

        private DateTime mDate = DateTime.Now.Date;

        public DateTime Date 
        {
            get { return mDate; }
            set { mDate = value; Notify( this ); }
        }

        [Browsable(false)]
        public IEnumerable<IOrderItem> Items { get { return mOrderItems;  } }

        [Browsable(true), XmlIgnore]
        public IClient Client
        {
            get { return mClient;  } 
            set { mClient = value; Notify(this);}
        }

        public void Append( IOrderItem aItem )
        {
            System.Diagnostics.Trace.Assert( ! Items.Contains( aItem ) );
            if ( Items.Contains( aItem ) ) return;
            ((ICollection<IOrderItem>)Items).Add( aItem );
        }

        public void Remove( IOrderItem aItem )
        {
            System.Diagnostics.Trace.Assert( Items.Contains( aItem ));
            if ( ! Items.Contains( aItem ) ) return;
            ( (ICollection<IOrderItem>) Items ).Remove( aItem );
        }
 
        public override string ToString()
        {
            var buffer = new StringBuilder();
            buffer.AppendFormat( "Order #{0}", Number );
            return buffer.ToString();
        }

        #region Serialization

        [Browsable(false), XmlElement("Client")]
        public string ClientId
        {
            get
            {
                return ( mClient != null ? mClient.Id.ToString() : "" );
            }
            set
            {
                mClient = Repository.Instance.Select<IClient>().FirstOrDefault( c => c.Id.ToString() == value );
            }
        }

        #endregion
    }
}
